﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using FDEEInterface;
using FDEEPublicFunc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FDEEDrawingModels
{
    public class PLotDeckSlabTable
    {
        #region 桥面板信息表

        /// <summary>
        /// 绘制桥面板
        /// </summary>
        /// <param name="db"></param>
        /// <param name="scale">比例默认1</param>
        /// <param name="filepath">模板数据路径</param>
        /// <param name="pierdiv">墩柱范围</param>
        /// <param name="title">所在线路</param>
        /// <param name="tkPath">图框路径</param>
        public static void DrawDeckSlabTable(Database db, double scale, string filepath,ref string pierdiv, string title = "MAINLINE", string tkPath = "")
        {
            Extents2d ext = new Extents2d(Point2d.Origin, Point2d.Origin);
            Extents2d ext1 = new Extents2d(Point2d.Origin, Point2d.Origin);
            Point2d CT = Point2d.Origin.Convert2D(0, -2 * scale);
            Point2d M1 = CT;
            ext = new Extents2d(M1, M1);

           
            //System.Data.DataTable dt = FDEECommonTools.CVSTools.OpenCSV(@"C:\Users\huajie\Documents\WXWork\1688856441293541\Cache\File\2022-04\FDEE.csv");
            System.Data.DataTable dt;
            //读取模板数据
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filepath);
            if (fileInfo.Extension.Contains("xlsx")) //xlsx格式
                dt = new FDEECommonTools.ExcelHelper().ExcelToTableForXLSX(filepath);
            else //csv格式
                dt = FDEECommonTools.CVSTools.OpenCSV(filepath);
            DataView dv0 = dt.DefaultView;
            //数据去重（csv表头0，1，2，3，4）
            dt = dv0.ToTable(true, new string[] { "0", "1", "2", "3", "4" });
            //列重命名
            dt.Columns[0].ColumnName = "pierName";
            dt.Columns[1].ColumnName = "station";
            dt.Columns[2].ColumnName = "DesignElevation";
            dt.Columns[3].ColumnName = "left";
            dt.Columns[4].ColumnName = "right";
            System.Data.DataTable dtP = new System.Data.DataTable();
            DataView dv = dt.DefaultView;
            //墩柱编号数据去重（csv表头1列）
            dtP = dv.ToTable(true, new string[] { "pierName" });
           
            List<DataRow> rowList = new List<DataRow>();
            //数据处理判断包含的墩号
            string oldvalue = "";
            foreach (DataRow dr in dtP.Rows)
            {
                //特殊数据处理
                DataRow row= dtP.Clone().NewRow();
                if (dr[0].ToString().Contains("-"))
                {
                    //包含-1之类的
                    row[0] = dr[0].ToString().Split('-')[0];
                   
                }
                else if (dr[0].ToString().Contains("."))
                {
                    //包含.1之类的
                    row[0] = dr[0].ToString().Split('.')[0];
                }
                else
                {
                    row[0] = dr[0].ToString();
                }
                //是否是新的编号，新编号添加
                if (oldvalue!= row[0].ToString())
                {
                    rowList.Add(row);
                    oldvalue = row[0].ToString(); 
                }
            }

            #region 分页处理
            List<Tuple<List<DataRow>, System.Data.DataTable>> tupleList=new List<Tuple<List<DataRow>, System.Data.DataTable>>() ;//分页组元列表       
            List<DataRow> pl = new List<DataRow>();//每一页的墩号列表
            System.Data.DataTable dtPierInfo  = dt.Clone();//每一页的数据信息列表

            int num = 0;
            for (int i = 0; i < rowList.Count; i++)
            {
                string pierNo = rowList[i]["pierName"].ToString();
                //获取包含当前墩号数据
                DataRow[] drs = dt.Select("pierName like '" + pierNo + "%'");
                num += drs.Length;
                //一页最多40行，每一页数据处理如下,40可以修改  
                if (i > 0)
                {
                    if (num<40)
                    {
                        pl.Add(rowList[i]);
                        for (int m = 0; m < drs.Length; m++)
                        {
                            dtPierInfo.Rows.Add(drs[m].ItemArray);
                        }

                    }
                    else
                    {
                        //当前页分页信息，用组元表达
                        Tuple<List<DataRow>, System.Data.DataTable> tuple = new Tuple<List<DataRow>, System.Data.DataTable>(pl, dtPierInfo);
                        tupleList.Add(tuple);
                        num = 0;
                        num += drs.Length;
                        pl = new List<DataRow>();
                        dtPierInfo = dt.Clone();
                        pl.Add(rowList[i]);
                        for (int m = 0; m < drs.Length; m++)
                        {
                            dtPierInfo.Rows.Add(drs[m].ItemArray);
                        }
                    }
                }
                else
                {
                    pl.Add(rowList[i]);
                    for (int m = 0; m < drs.Length; m++)
                    {
                        dtPierInfo.Rows.Add(drs[m].ItemArray);
                    }
                }
                if (i == rowList.Count - 1)
                {
                    //最后一页分页信息，用组元表达
                    Tuple<List<DataRow>, System.Data.DataTable> tuple = new Tuple<List<DataRow>, System.Data.DataTable>(pl, dtPierInfo);
                    tupleList.Add(tuple);
                }
            }
            #endregion

            for (int page = 0; page < tupleList.Count; page++)
            {
                List<DataRow> rowP = tupleList[page].Item1;
                System.Data.DataTable dtPier= tupleList[page].Item2;
                if (rowP.Count > 0)
                {
                    //起始墩号
                    string stNo = rowP[0][0].ToString();
                    string endNo = rowP[rowP.Count - 1][0].ToString();
                    if(rowP[0][0].ToString().Contains("RP"))
                        pierdiv = stNo + "-" + endNo;
                    else
                    pierdiv = "P" + stNo + "-" + endNo;
                    //CAD表格定义
                    Table lasTb = new Table();
                    //CAD表格区域范围定义
                    ext = new Extents2d(M1.Convert2D(420* page), M1.Convert2D(420 * page));

                    //表格绘制
                    lasTb = DrawingDeckSlabInfomationTable(db, ref ext, M1.Convert3D(420 * page),
                        Extensions.curFont, scale, dtPier, rowP, title);
                    double width = lasTb.Width * 0.5;
                    if (lasTb != null)
                    {
                        //标题
                        string str1 = string.Format("ELEVATION TABLE OF DECK SLAB FOR '{0}' TO '{1}' OF {2}", "P-" + stNo, "P-" + endNo, title);
                        if(stNo.Contains("RP"))
                            str1 = string.Format("ELEVATION TABLE OF DECK SLAB FOR '{0}' TO '{1}' OF {2}", stNo,  endNo, title);
                        string str2 = "";
                        //添加标题
                        TextPloter.PrintScaleDoubleSideText(db, M1.Convert2D(420 * page, 0).Convert2D(width, 5 * scale), 3, str1, str2, ref ext, scale, Extensions.curFont);
                    }
                    //创建布局空间，模型空间投影到布局空间视口
                    Common.CreateLayoutNew(db, "桥面板信息表", ext, scale, 1, 0, page, false, tkPath);
                }

            }
            //if (rowList.Count > 0)
            //{
            //    //起始墩号
            //    string stNo = rowList[0][0].ToString();
            //    string endNo = rowList[rowList.Count - 1][0].ToString();
            //    pierdiv = "P"+stNo + "-" + endNo;
            //    //CAD表格定义
            //    Table lasTb = new Table();
            //    //CAD表格区域范围定义
            //    ext = new Extents2d(M1.Convert2D(), M1.Convert2D());

            //    //表格绘制
            //    lasTb = DrawingDeckSlabInfomationTable(db, ref ext, M1.Convert3D(),
            //        Extensions.curFont, scale, dt, rowList, title);
            //    double width = lasTb.Width*0.5;
            //    if (lasTb != null)
            //    {
            //        //标题
            //        string str1 = string.Format("ELEVATION TABLE OF DECK SLAB FOR '{0}' TO '{1}' OF {2}", "P-" + stNo, "P-" + endNo, title);
            //        string str2 = "";
            //        //添加标题
            //        TextPloter.PrintScaleDoubleSideText(db, M1.Convert2D(0, 0).Convert2D(width, 5 * scale), 3, str1, str2, ref ext, scale, Extensions.curFont);
            //    }
            //    //创建布局空间，模型空间投影到布局空间视口
            //    Common.CreateLayoutNew(db, "桥面板信息表", ext, scale, 1, 0, 0, false, tkPath);
            //}
        }

        /// <summary>
        /// 桥面板信息表格绘制
        /// </summary>
        /// <param name="db"></param>
        /// <param name="ext"></param>
        /// <param name="startPoint">插入位置</param>
        /// <param name="txtStyle">字体</param>
        /// <param name="scale">比例</param>
        /// <param name="tbData">数据表格</param>
        /// <param name="rows">墩柱列表</param>
        /// <param name="Title"></param>
        /// <returns></returns>
        public static Table DrawingDeckSlabInfomationTable(Database db, ref Extents2d ext, Point3d startPoint,
string txtStyle, double scale, System.Data.DataTable tbData, List<DataRow> rows, string Title = "MAINLINE")
        {

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                //CAD 绘制默认定义
                BlockTable blockTbl = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                //模型空间数据列表定义
                BlockTableRecord modelSpace = tr.GetObject(blockTbl[BlockTableRecord.ModelSpace],
                    OpenMode.ForWrite) as BlockTableRecord;
                //获取字体样式
                ObjectId id;
                TextStyleTable st = tr.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
                id = st[txtStyle];

                #region  表格
                //定义表格
                Table tb = new Table();

                //表格列数
                int colNum = 6;
                if(Title !="MAINLINE")
                    colNum = 5;
                //表格行数
                int rowNum = tbData.Rows.Count + 1;

                //设置要绘制的表格行数和列数
                tb.SetSize(rowNum, colNum);       // 设置几行几列
                //表格插入位置
                tb.Position = startPoint.Convert3D();
                tb.GenerateLayout();

                #region 设置列宽
                // 设置列宽
                for (int i = 0; i < colNum; ++i)
                {
                    if(i==1)
                        tb.Columns[i].Width = 15 * 3 * scale;
                    else
                         tb.Columns[i].Width = 8 * 3 * scale;
                }


                //设置行高
                for (int i = 0; i < rowNum; ++i)
                {
                    if (i == 0)
                        tb.Rows[i].Height = 9 * scale;
                    else
                        tb.Rows[i].Height = 5.7 * scale;
                }
                #endregion

                #region 表头

                tb.Cells[0, 0].TextString = "Pier No."; //获取0行0列表头数据
                tb.Cells[0, 0].Contents[0].TextHeight = 2 * scale;
                tb.Cells[0, 0].Alignment = CellAlignment.MiddleCenter;
                tb.Cells[0, 0].Contents[0].Rotation = 0;
                tb.Cells[0, 0].Borders.Horizontal.Margin = 1 * scale;
                tb.Cells[0, 0].Contents[0].TextStyleId = id;


                tb.Cells[0, 1].TextString = "Deck slab width at the top of pier\\P (m)"; //获取0行1列表头数据
                tb.Cells[0, 1].Contents[0].TextHeight = 2 * scale;
                tb.Cells[0, 1].Alignment = CellAlignment.MiddleCenter;
                tb.Cells[0, 1].Contents[0].Rotation = 0;
                tb.Cells[0, 1].Borders.Horizontal.Margin = 1 * scale;
                tb.Cells[0, 1].Contents[0].TextStyleId = id;


                tb.Cells[0, 2].TextString = "Station"; //获取0行2列表头数据
                tb.Cells[0, 2].Contents[0].TextHeight = 2 * scale;
                tb.Cells[0, 2].Alignment = CellAlignment.MiddleCenter;
                tb.Cells[0, 2].Contents[0].Rotation = 0;
                tb.Cells[0, 2].Borders.Horizontal.Margin = 1 * scale;
                tb.Cells[0, 2].Contents[0].TextStyleId = id;


                tb.Cells[0, 3].TextString = "Design Elevation\\P (m)"; //获取0行3列表头数据
                tb.Cells[0, 3].Contents[0].TextHeight = 2 * scale;
                tb.Cells[0, 3].Alignment = CellAlignment.MiddleCenter;
                tb.Cells[0, 3].Contents[0].Rotation = 0;
                tb.Cells[0, 3].Borders.Horizontal.Margin = 1 * scale;
                tb.Cells[0, 3].Contents[0].TextStyleId = id;

                if (Title == "MAINLINE")
                {
                    tb.Cells[0, 4].TextString = "Super Elevation\\P Left"; //获取0行4列表头数据
                    tb.Cells[0, 4].Contents[0].TextHeight = 2 * scale;
                    tb.Cells[0, 4].Alignment = CellAlignment.MiddleCenter;
                    tb.Cells[0, 4].Contents[0].Rotation = 0;
                    tb.Cells[0, 4].Borders.Horizontal.Margin = 1 * scale;
                    tb.Cells[0, 4].Contents[0].TextStyleId = id;


                    tb.Cells[0, 5].TextString = "Super Elevation\\P Right"; //获取0行5列表头数据
                    tb.Cells[0, 5].Contents[0].TextHeight = 2 * scale;
                    tb.Cells[0, 5].Alignment = CellAlignment.MiddleCenter;
                    tb.Cells[0, 5].Contents[0].Rotation = 0;
                    tb.Cells[0, 5].Borders.Horizontal.Margin = 1 * scale;
                    tb.Cells[0, 5].Contents[0].TextStyleId = id;
                }
                else
                {
                    tb.Cells[0, 4].TextString = "Super Elevation"; //获取0行4列表头数据
                    tb.Cells[0, 4].Contents[0].TextHeight = 2 * scale;
                    tb.Cells[0, 4].Alignment = CellAlignment.MiddleCenter;
                    tb.Cells[0, 4].Contents[0].Rotation = 0;
                    tb.Cells[0, 4].Borders.Horizontal.Margin = 1 * scale;
                    tb.Cells[0, 4].Contents[0].TextStyleId = id;

                }
                #endregion

                #region 设置表格值
                int rowCount = 0;
                int num=0;//第几个墩
                int no = 0;//当前
                for (int i = 0; i < tbData.Rows.Count; i++)
                {
                    //墩号
                    string pierNo = rows[num]["pierName"].ToString();
                    //获取包含当前墩号数据
                    DataRow[] drs = tbData.Select("pierName like '" + pierNo + "%'");
                    rowCount = drs.Length;//当前墩号数量
                    if (no == rowCount)
                    {
                        num++;
                        no = 1;
                        pierNo = rows[num]["pierName"].ToString();
                        drs = tbData.Select("pierName like '" + pierNo + "%'");
                        rowCount = drs.Length;//当前墩号数量
                    }
                  
                    if (pierNo == tbData.Rows[i]["pierName"].ToString())
                    {
                        if (pierNo.Contains("RP"))
                            //设置第1+i行0列数据
                            tb.Cells[1 + i, 0].TextString =pierNo;
                        else
                            tb.Cells[1 + i, 0].TextString = "P-" + pierNo.Replace("P","");
                        tb.Cells[1 + i, 0].Contents[0].TextHeight = 2 * scale;
                        tb.Cells[1 + i, 0].Alignment = CellAlignment.MiddleCenter;
                        tb.Cells[1 + i, 0].Contents[0].Rotation = 0;
                        tb.Cells[1 + i, 0].Borders.Horizontal.Margin = 1 * scale;
                        tb.Cells[1 + i, 0].Contents[0].TextStyleId = id;
                        //合并
                        tb.MergeCells(CellRange.Create(tb, 1 + i, 0, 1 + i + rowCount-1, 0));
                        //设置第1+i行1列数据
                        tb.Cells[1 + i, 1].TextString = "20.56";
                        tb.Cells[1 + i, 1].Contents[0].TextHeight = 2 * scale;
                        tb.Cells[1 + i, 1].Alignment = CellAlignment.MiddleCenter;
                        tb.Cells[1 + i, 1].Contents[0].Rotation = 0;
                        tb.Cells[1 + i, 1].Borders.Horizontal.Margin = 1 * scale;
                        tb.Cells[1 + i, 1].Contents[0].TextStyleId = id;
                        //合并
                        tb.MergeCells(CellRange.Create(tb, 1 + i, 1, 1 + i + rowCount - 1, 1));

                        no = 1;
                    }
                    else
                    {
                        no++;
                    }
                    string station = double.Parse(tbData.Rows[i]["station"].ToString()).ToString("0.000");
                    string sta = "0";
                    sta = tbData.Rows[i]["station"].ToString().Substring(0, station.Length - 7);
                    if(string.IsNullOrWhiteSpace(sta))
                    {
                        sta = "0";
                    }
                    //设置第1+i行2列数据
                    tb.Cells[1 + i, 2].TextString = sta + "+" + station.Substring(station.Length - 7);
                    tb.Cells[1 + i, 2].Contents[0].TextHeight = 2 * scale;
                    tb.Cells[1 + i, 2].Alignment = CellAlignment.MiddleCenter;
                    tb.Cells[1 + i, 2].Contents[0].Rotation = 0;
                    tb.Cells[1 + i, 2].Borders.Horizontal.Margin = 1 * scale;
                    tb.Cells[1 + i, 2].Contents[0].TextStyleId = id;


                    //设置第1+i行3列数据
                    tb.Cells[1 + i, 3].TextString = double.Parse(tbData.Rows[i]["DesignElevation"].ToString()).ToString("0.000");
                    tb.Cells[1 + i, 3].Contents[0].TextHeight = 2 * scale;
                    tb.Cells[1 + i, 3].Alignment = CellAlignment.MiddleCenter;
                    tb.Cells[1 + i, 3].Contents[0].Rotation = 0;
                    tb.Cells[1 + i, 3].Borders.Horizontal.Margin = 1 * scale;
                    tb.Cells[1 + i, 3].Contents[0].TextStyleId = id;

                    //设置第1+i行4列数据
                    tb.Cells[1 + i, 4].TextString = Math.Abs(double.Parse(tbData.Rows[i]["left"].ToString())).ToString("0.0") + "%";
                    tb.Cells[1 + i, 4].Contents[0].TextHeight = 2 * scale;
                    tb.Cells[1 + i, 4].Alignment = CellAlignment.MiddleCenter;
                    tb.Cells[1 + i, 4].Contents[0].Rotation = 0;
                    tb.Cells[1 + i, 4].Borders.Horizontal.Margin = 1 * scale;
                    tb.Cells[1 + i, 4].Contents[0].TextStyleId = id;
                    if (Title == "MAINLINE")
                    { 
                        //设置第1+i行5列数据
                        tb.Cells[1 + i, 5].TextString = Math.Abs(double.Parse(tbData.Rows[i]["right"].ToString())).ToString("0.0")+"%";
                    tb.Cells[1 + i, 5].Contents[0].TextHeight = 2 * scale;
                    tb.Cells[1 + i, 5].Alignment = CellAlignment.MiddleCenter;
                    tb.Cells[1 + i, 5].Contents[0].Rotation = 0;
                    tb.Cells[1 + i, 5].Borders.Horizontal.Margin = 1 * scale;
                    tb.Cells[1 + i, 5].Contents[0].TextStyleId = id;
                        }
       

                }
                #endregion
                //设置图层
                tb.Layer = "细线";
                //设置线宽
                tb.LineWeight = LineWeight.LineWeight013;
                //设置表格颜色
                tb.ColorIndex = 4;
                modelSpace.AppendEntity(tb);
                tr.AddNewlyCreatedDBObject(tb, true);
                //获取表格绘制范围
                ext = ext.Add(new Extents2d(tb.Bounds.Value.MinPoint.Convert2D(), tb.Bounds.Value.MaxPoint.Convert2D()));

                #endregion

                #region  边框设置粗线
                List<Point2d> pList = new List<Point2d>();
                Point2d pt1 = startPoint.Convert2D();
                pList.Add(pt1);
                Point2d pt2 = pt1.Convert2D(0, -tb.Height);
                pList.Add(pt2);
                Point2d pt3 = pt1.Convert2D(tb.Width, -tb.Height);
                pList.Add(pt3);
                Point2d pt4 = pt1.Convert2D(tb.Width, 0);
                pList.Add(pt4);
                PolylinePloter.AddPolylineByList(db, ref ext, pList, "粗线", 2);
                #endregion               

                tr.Commit();
                return tb;
            }
        }


        /// <summary>
        /// 绘制桥面板
        /// </summary>
        /// <param name="db"></param>
        /// <param name="scale">比例默认1</param>
        /// <param name="filepath">模板数据路径</param>
        /// <param name="pierdiv">墩柱范围</param>
        /// <param name="title">所在线路</param>
        /// <param name="tkPath">图框路径</param>
        public static void DrawDeckSlabRebarTable(Database db, double scale, string filepath,  string title = "MAINLINE", string tkPath = "")
        {
            Extents2d ext = new Extents2d(Point2d.Origin, Point2d.Origin);
            Extents2d ext1 = new Extents2d(Point2d.Origin, Point2d.Origin);
            Point2d CT = Point2d.Origin.Convert2D(0, -2 * scale);
            Point2d M1 = CT;
            ext = new Extents2d(M1, M1);
        }


        #endregion
    }
}
